import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:raze/lore/chronicle/diary_chronicle.dart';
import 'package:raze/lore/chronicle/diary_guidance_chronicle.dart';
import 'package:raze/lore/chronicle/user_chronicle.dart';
import 'package:raze/potions/raze_constant.dart';
import 'package:raze/potions/spatial_alchemy.dart';

/// 日志页面
class DiaryRealms extends StatelessWidget {
  const DiaryRealms({super.key});

  @override
  Widget build(BuildContext context) {
    // 初始化引导状态管理
    final guidanceChronicle = Get.put(DiaryGuidanceChronicle());
    final diaryChronicle = Get.find<DiaryChronicle>();
    final userChronicle = Get.find<UserChronicle>();

    return Container(
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/background.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: Stack(
          children: [
            // 主要内容
            SafeArea(
              bottom: false,
              child: Column(
                children: [
                  // 顶部标题栏
                  _assembleTitleBar(),

                  // 日志内容区域
                  Expanded(
                    child: Obx(() {
                      final currentUser = userChronicle.currentUser;
                      if (currentUser == null) {
                        // 未登录状态
                        return _constructNotLoggedInView();
                      }

                      // 已登录，显示日志列表
                      final userDiaries = diaryChronicle.fetchUserDiaries(
                        currentUser.id,
                      );

                      if (userDiaries.isEmpty) {
                        return _constructEmptyDiaryView();
                      }

                      return _constructDiaryGridView(userDiaries);
                    }),
                  ),
                ],
              ),
            ),

            // 引导蒙层（覆盖整个屏幕，包括状态栏）
            Obx(() {
              if (!guidanceChronicle.showGuidance) {
                return const SizedBox.shrink();
              }

              return Positioned.fill(
                child: _constructGuidanceOverlay(guidanceChronicle),
              );
            }),
          ],
        ),
      ),
    );
  }

  /// 组装顶部标题栏
  Widget _assembleTitleBar() {
    return Container(
      padding: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('Rain Journal')
              .applyTypeSize(24.sp)
              .applyTypeColor(RazeConstants.black)
              .applyBagelFatOne(weight: FontWeight.w400),
          8.w.boxWidth,
          // 装饰图片
          Image.asset(
            'assets/images/diary-decoration.png',
            width: 36.w,
            height: 36.w,
            fit: BoxFit.contain,
          ),
        ],
      ),
    );
  }

  /// 构建未登录视图
  Widget _constructNotLoggedInView() {
    return Center(
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 32.w),
        child: Column(
          children: [
            100.h.boxHeight,
            // 装饰图片
            Image.asset(
              'assets/images/empty-status.png',
              width: 200.w,
              height: 200.w,
              fit: BoxFit.contain,
            ),

            // 提示文字容器
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
              decoration: BoxDecoration(
                color: RazeConstants.white,
                borderRadius: BorderRadius.circular(16.r),
                border: Border.all(color: RazeConstants.black, width: 2.w),
              ),
              child: Text('Please login to view your diary')
                  .applyTypeSize(16.sp)
                  .applyTypeColor(RazeConstants.black)
                  .applyNotoSans(weight: FontWeight.w500),
            ).withRightBottomShadow(thickness: 1),

            16.h.boxHeight,

            // 前往登录按钮
            Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 24.w,
                    vertical: 12.h,
                  ),
                  decoration: BoxDecoration(
                    color: RazeConstants.yellow,
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(color: RazeConstants.black, width: 2.w),
                  ),
                  child: Text('Go to Login')
                      .applyTypeSize(16.sp)
                      .applyTypeColor(RazeConstants.black)
                      .applyNotoSans(weight: FontWeight.w600),
                )
                .withRightBottomShadow(thickness: 1.5)
                .withTouchResonance(
                  onTap: () {
                    Get.toNamed('/login');
                  },
                ),
          ],
        ),
      ),
    );
  }

  /// 构建空日志视图
  Widget _constructEmptyDiaryView() {
    return Center(
      child:
          Text('No diary entries yet')
              .applyTypeSize(16.sp)
              .applyTypeColor(RazeConstants.black.withOpacity(0.6))
              .applyNotoSans(),
    );
  }

  /// 构建日志网格视图（两列）
  Widget _constructDiaryGridView(List userDiaries) {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: LayoutBuilder(
        builder: (context, constraints) {
          // 单个日志项的宽度
          final spacing = 12.w;
          final columnSpacing = 30.w;
          final availableWidth = constraints.maxWidth;
          final itemWidth = (availableWidth - spacing) / 2;

          return Wrap(
            alignment: WrapAlignment.start,
            spacing: spacing,
            runSpacing: columnSpacing,
            children:
                userDiaries.asMap().entries.map((entry) {
                  final diary = entry.value;
                  return _constructDiaryCard(diary, itemWidth);
                }).toList(),
          );
        },
      ),
    );
  }

  /// 构建单个日志卡片
  Widget _constructDiaryCard(dynamic diary, double itemWidth) {
    // 主容器宽高比 166 / 198
    final containerAspectRatio = 166 / 198;
    final containerHeight = itemWidth / containerAspectRatio;

    // 图片宽高比 140 / 130
    final imageAspectRatio = 140 / 130;
    final imagePadding = 10.w;
    final imageWidth = itemWidth - (imagePadding * 2);

    // 计算可用高度：容器高度 - 图片上下padding - 文字区域预留高度 - 按钮预留空间
    final textPaddingTop = 5.h;
    final textPaddingBottom = 3.h;
    final buttonSpace = 18.h; // 按钮一半高度（按钮总高约36.h，一半为18.h）
    // 估算文字区域高度（1行文字约16.h + 间距3.h + 日期约14.h）
    final estimatedTextHeight = 16.h + 3.h + 14.h;
    final textAreaHeight =
        textPaddingTop + estimatedTextHeight + textPaddingBottom;
    final availableImageHeight =
        containerHeight - (imagePadding * 2) - textAreaHeight - buttonSpace;

    // 根据可用高度计算图片实际高度（不能超过按宽高比计算的高度）
    final idealImageHeight = imageWidth / imageAspectRatio;
    final imageHeight =
        idealImageHeight > availableImageHeight
            ? availableImageHeight
            : idealImageHeight;

    return GestureDetector(
      onTap: () {
        // 跳转到日志详情页面
        Get.toNamed('/diary-detail', parameters: {'diaryId': diary.id});
      },
      child: SizedBox(
        width: itemWidth,
        height: containerHeight,
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            // 主容器
            Container(
              decoration: BoxDecoration(
                color: RazeConstants.white,
                borderRadius: BorderRadius.circular(19.r),
                border: Border.all(color: RazeConstants.black, width: 2.w),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 图片部分（带内边距）
                  Padding(
                    padding: EdgeInsets.only(
                      top: 5.h,
                      left: imagePadding,
                      right: imagePadding,
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(19.r),
                      child: SizedBox(
                        width: imageWidth,
                        height: imageHeight,
                        child:
                            diary.contentType == 'video'
                                ? Stack(
                                  fit: StackFit.expand,
                                  children: [
                                    // 视频封面
                                    Image.asset(
                                      diary.coverImage ?? diary.media,
                                      fit: BoxFit.fill,
                                    ),
                                    // 播放图标
                                    Center(
                                      child: Container(
                                        padding: EdgeInsets.all(8.w),
                                        decoration: BoxDecoration(
                                          color: RazeConstants.black
                                              .withOpacity(0.5),
                                          shape: BoxShape.circle,
                                        ),
                                        child: Icon(
                                          Icons.play_arrow_rounded,
                                          size: 24.sp,
                                          color: RazeConstants.white,
                                        ),
                                      ),
                                    ),
                                  ],
                                )
                                : Image.asset(diary.media, fit: BoxFit.fill),
                      ),
                    ),
                  ),

                  // 文字部分
                  Padding(
                    padding: EdgeInsets.only(
                      left: imagePadding,
                      right: imagePadding,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // 详情文字（只显示1行）
                        Text(
                          diary.detail,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 13.sp,
                            color: RazeConstants.black,
                            fontFamily:
                                GoogleFonts.notoSans(
                                  fontWeight: FontWeight.w600,
                                ).fontFamily,
                          ),
                        ),

                        // 日期
                        Text(
                          _formatDate(diary.createTime),
                          style: TextStyle(
                            fontSize: 10.sp,
                            color: RazeConstants.black.withOpacity(0.7),
                            fontFamily:
                                GoogleFonts.notoSans(
                                  fontWeight: FontWeight.w400,
                                ).fontFamily,
                          ),
                        ),
                      ],
                    ),
                  ),

                  // 为按钮留出一半的空间（按钮一半在容器内，一半在容器外）
                  // 按钮高度约为：padding(10.h*2) + 文字高度(约16.h) ≈ 36.h
                  // 一半高度约为 18.h
                  SizedBox(height: 28.h),
                ],
              ),
            ).withRightBottomShadow(thickness: 1.5),

            // 详情按钮（一半在容器内，一半在容器外）
            Positioned(
              bottom: -12.h, // 按钮一半高度在容器外
              left: 0,
              right: 0,
              child: Center(
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 24.w,
                    vertical: 10.h,
                  ),
                  decoration: BoxDecoration(
                    color: RazeConstants.blue,
                    borderRadius: BorderRadius.circular(10.r),
                    border: Border.all(color: RazeConstants.black, width: 2.w),
                  ),
                  child: Text('Details')
                      .applyTypeSize(14.sp)
                      .applyTypeColor(RazeConstants.white)
                      .applyNotoSans(weight: FontWeight.w600),
                ).withRightBottomShadow(thickness: 2),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建引导蒙层
  Widget _constructGuidanceOverlay(DiaryGuidanceChronicle guidanceChronicle) {
    // 宽高比 310 / 415
    final aspectRatio = 310 / 415;

    return Container(
      color: RazeConstants.black.withOpacity(0.5),
      child: Center(
        child: LayoutBuilder(
          builder: (context, constraints) {
            // 根据屏幕宽度计算图片尺寸
            final maxWidth = constraints.maxWidth * 0.85;
            final imageWidth = maxWidth.clamp(0.0, 310.w).toDouble();
            final imageHeight = imageWidth / aspectRatio;

            return Stack(
              children: [
                // 引导图片
                Padding(
                  padding: EdgeInsets.only(top: 130.h),
                  child: SizedBox(
                    width: imageWidth,
                    height: imageHeight,
                    child: Image.asset(
                      'assets/images/guidance.png',
                      fit: BoxFit.contain,
                    ),
                  ),
                ),

                // 关闭按钮（图片右上角）
                Positioned(
                  top: 130.h,
                  right: 10.w,
                  child: GestureDetector(
                    onTap: () {
                      // 点击关闭按钮关闭蒙层
                      guidanceChronicle.dismissGuidance();
                    },
                    child: Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                        color: Colors.transparent,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.close_rounded,
                        size: 24.sp,
                        color: Colors.transparent,
                      ),
                    ),
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }

  /// 格式化日期
  String _formatDate(DateTime dateTime) {
    final year = dateTime.year;
    final month = dateTime.month.toString().padLeft(2, '0');
    final day = dateTime.day.toString().padLeft(2, '0');
    return '$year-$month-$day';
  }
}
